package job

import (
	"git.multiverse.io/eventkit/dxc-server/config"
	"git.multiverse.io/eventkit/dxc-server/models"
	"git.multiverse.io/eventkit/dxc-server/repo"
	"git.multiverse.io/eventkit/kit/contexts"
	"git.multiverse.io/framework/log"
	"time"
)

func StartTimeExpiredRecordsRecoverJob() {
	log.Infos("Start time expired records recover jobs")
	defer log.Infos("Successfully started time expired records recover jobs")

	repository := repo.RepositoryInstance()
	go expireTimeRecoverWorker(repository)
}

func expireTimeRecoverWorker(repository repo.Repository) {
	t := time.NewTicker(time.Second * 1)
	for {
		select {
		case <-t.C:
			rootBranches, err := repository.FindRootBranchesByTimeExpire(config.Cfg.Service.ExpireTimeSeconds)
			if err != nil {
				log.Errorsf("Start ExpireTime Recover Job: FindRootBranchesByTimeExpire from memory fail, err:%s", err)
				break
			}
			for _, rootBranch := range rootBranches {
				rootXid := rootBranch.RootXid
				log.Debugsf("Start ExpireTime Recover Job: Push Queue Recover rootXid:[%s]", rootXid)
				spanCtx := contexts.BuildSpanContexts(contexts.TraceID(rootBranch.ParentXid),
					contexts.ParentSpanID(rootXid),
					contexts.TimeoutMilliseconds(30000),
				)
				pair := models.Pair{
					RootXid:  rootXid,
					SpanCtx:  spanCtx,
					RootType: models.TimeExpiredRecordsRecover,
					Type:     models.TimeExpiredRecordsRecover,
				}
				models.Queue.Push(pair)
			}
		}
	}
}
